#include <stdio.h>
#include <string.h>
#include <hs/hs.h>

// 回调函数
int on_match(unsigned int id, unsigned long long from,
        unsigned long long to, unsigned int flags, void *ctx);

int main(int argc, char *argv[])
{
    hs_database_t *database = NULL;
    hs_compile_error_t *compile_err = NULL;
    hs_error_t err;

    // 编译正则表达式
    const char *regex = "hello|world";
    err = hs_compile(regex, HS_FLAG_CASELESS, HS_MODE_BLOCK,
                     NULL, &database, &compile_err);
    if (err != HS_SUCCESS) {
        fprintf(stderr, "Error compiling pattern: %s\n",
                compile_err->message);
        hs_free_compile_error(compile_err);
        return 1;
    }

    // 分配临时空间(指针必须初始化为NULL)
    hs_scratch_t *scratch = NULL;
    err = hs_alloc_scratch(database, &scratch);
    if (err != HS_SUCCESS) {
        fprintf(stderr, "Error allocating scratch space\n");
        hs_free_database(database);
        return 1;
    }

    // 单模+块扫描
    int flag = 0;
    const char *input = "Hello, world!";
    err = hs_scan(database, input, strlen(input), 0, scratch,
                  on_match, &flag);
    if (err != HS_SUCCESS) {
        fprintf(stderr, "Error scanning input\n");
        hs_free_scratch(scratch);
        hs_free_database(database);
        return 1;
    }

    printf("flag = %d\n", flag);

    // 释放空间
    hs_free_scratch(scratch);
    hs_free_database(database);

    return 0;
}

int on_match(unsigned int id, unsigned long long from,
        unsigned long long to, unsigned int flags, void *ctx)
{
    int *tmp = (int*)ctx;
    *tmp = 1;

    printf("Match found at end offset %llu, id %u\n", to, id);

    return 0;
}
